# encoding=utf-8
"""
响应对象业务校验
"""
import json
from scrapy.exceptions import IgnoreRequest
from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request


class BizValidator(BaseValidateMiddleware):

    def validate_sku(self, request, response, spider):
        if not response.text:
            return retry_request(request)

        meta = request.meta
        catalog_id = meta.get('catalogId')
        supplier_id = meta.get('supplierId')
        page = meta.get('page')
        rs = json.loads(response.text)
        if not rs:
            raise IgnoreRequest('[Sku]响应数据无效: <shopId=%s, fcids=%s, pageNo=%s>' % (supplier_id, catalog_id, page))

        entities = rs.get('searchWithAggs').get('entities', None)
        if not entities or entities.get('empty'):
            raise IgnoreRequest('[Sku]响应商品为空: <shopId=%s, fcids=%s, pageNo=%s>' % (supplier_id, catalog_id, page))

        return response

    def validate_item(self, request, response, spider):
        if not response.text:
            return retry_request(request)

        meta = request.meta
        sku_id = meta.get('skuId')

        # 特殊处理
        # if sku_id == '33254975':
        #     raise IgnoreRequest('抛弃错误数据: [%s]' % sku_id)

        js = json.loads(response.text)
        if not js.get('success', False) or 'result' not in js:
            raise IgnoreRequest('[Item][%s]%s' % (sku_id, js.get('error', '异常1: 响应结构异常')))

        result = js.get('result', {})
        if not result:
            raise IgnoreRequest('[Item][%s]下架' % sku_id)
        item = result.get('item', None)
        if not item:
            raise IgnoreRequest('[Item][%s]异常2: item不存在' % sku_id)

        skus = result.get('skus', [])
        if not skus or len(skus) == 0:
            raise IgnoreRequest('[Item][%s]异常3: skus不存在' % sku_id)

        return response

    def validate_order(self, request, response, spider):
        if response.text:
            return response
        elif response.status == 200 and not response.text:
            raise IgnoreRequest('[Order]无单: [%s]' % request.meta.get('skuId'))
        else:
            raise IgnoreRequest('[Order]响应异常: [%s]' % response)
